package uml.behavioral.observer.ext;

import org.xml.sax.SAXException;
import util.xml.XMLUtil;

import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;

/**
 * on 2023/1/4 17:05
 */
public class TransLight extends Light {
    @Override
    public void notice() {
        for (Driver driver : drivers) {
            driver.actAccordingTo(this);
        }
    }

    @Override
    public void changeState() throws ParserConfigurationException, IOException, SAXException, InterruptedException {
        File config = new File("src/main/resources/xml/observer.xml");
        String redTime = "redTime", greenTime = "greenTime", yellowTime = "yellowTime",
                red = "红灯", green = "绿灯", yellow = "黄灯";
        while (true) {
            countDown(config, yellowTime, yellow);
            countDown(config, redTime, red);
            countDown(config, greenTime, green);
        }
    }

    private void countDown(File config, String tagName, String state) throws ParserConfigurationException, IOException, SAXException, InterruptedException {
        lightTime = Integer.valueOf(XMLUtil.getValueOfFirstTagOfConfigFile(config, tagName));
        while (lightTime >= 0) {
            this.state = state;
            notice();
            Thread.sleep(1000);
            lightTime--;
        }
    }
}
